package com.project.ssmfo.common;

import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;

import com.project.ssmfo.model.SysUser;
import com.project.utils.UserAgent;
import com.project.utils.UserAgentUtil;


/**
 * @ClassName: UserOperateLogInterceptor
 * @Description: 用户操作日志拦截器
 * 				用于记录用户在平台中的操作信息
 * @Author  
 * @Create
 */
public class UserOperateLogInterceptor extends HandlerInterceptorAdapter{
    static final Logger log = LoggerFactory.getLogger("SystemUserOperateLog");
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler){
    	String remoteIP = getRemoteIP(request);
    	SysUser currentUser = (SysUser)request.getSession().getAttribute("currentUser");
    	String username = (currentUser == null || currentUser.getUserName() == null) ? "unlogin" : currentUser.getUserName();
    	String requestURI = request.getRequestURI();
    	log.info("[OperateLog]Action: [" + requestURI + "] \tUser:" + username + "\tIP:" + remoteIP);
    	int index = requestURI.lastIndexOf(";JSESSIONID");
		
    	requestURI = index==-1?requestURI:requestURI.substring(0, index);
    	
    	if(requestURI.indexOf("/WEB-INF/") != -1 || requestURI.indexOf("/static/") != -1 || 
    			requestURI.indexOf(".jsp") != -1 || requestURI.indexOf(".html") != -1 || 
    					requestURI.indexOf(".js") != -1 || requestURI.indexOf(".css") != -1 ) {  
			// 跳过所有由于项目自己页面跳转引起的请求信息
    		return true;
		}
    	
		UserAgent userAgent = UserAgentUtil.getUserAgent(request.getHeader("user-agent"));
		if(currentUser == null || currentUser.getId() == null || currentUser.getId() <= 0) {
			String moudleName = ""; // 请求的模块名
			String actionName = ""; // 指定的方法名
			String actionString = "";
			
			//判断是否ajax请求   前端接口请求
	        String header = request.getHeader("X-Requested-With");  
	        boolean isAjax = "XMLHttpRequest".equalsIgnoreCase(header);

			StringBuilder params = new StringBuilder();
			Enumeration<String> enu = request.getParameterNames();
			while(enu.hasMoreElements()){	
				String paraName=(String)enu.nextElement();
				if (params.length() > 0) {
					params.append('&');
				}
				params.append(paraName);
				params.append('=');
				params.append(request.getParameter(paraName));
			}
			
			if (moudleName.length() <= 0) {
				moudleName = requestURI;
			}
			
			String [] targetParts = actionString.split("\\/");
			if(targetParts.length>0) {
				actionName = targetParts[targetParts.length-1].trim();
			}

			if ( actionName == null || actionName.length() <= 0) {
				actionName = "index";
			}
			
			//放入redis缓存
			String redis_open = Configuration.get("redis_open");
			if("1".equals(redis_open)){
				log.info("operate record save to redis start...."+redisTemplate.opsForList().size("operaRecord"));
//				String redis_cachename = Configuration.get("redis_cachename");
	//			Cache logCache = Redis.use(redis_cachename);
//				System.out.println("******************"+redisTemplate.opsForList().range("operaRecord", 0, 1));
				Map<String,Object> map=new HashMap<String,Object>();
				if (userAgent == null) {
					map.put("platform", "未知");
					map.put("browser", "未知");
				} else {
					map.put("platform",request.getHeader("user-agent"));
					map.put("browser",userAgent.getBrowserType() + " " + userAgent.getBrowserVersion());
					
				}
				map.put("method",request.getMethod());
				map.put("is_ajax",isAjax);
				map.put("moudle","dssums1.0"+moudleName);
				map.put("action",actionName);
				map.put("parameter",params.toString());
				map.put("referer",request.getHeader("referer"));
				map.put("create_date",new Date());
				map.put("update_date",new Date());
				map.put("del_flag", 0);
				//
				redisTemplate.opsForList().rightPushAll("operaRecord", JSON.toJSONString(map));
//				redisTemplate.opsForList().trim("operaRecord", 10, -1);
				log.info("operate record save to redis end...."+redisTemplate.opsForList().size("operaRecord"));
				
			}
		}
        return true;
    }
    
	/**
	 * @Title: getRemortIP
	 * @Description: 获取用户请求ip
	 * @param request
	 * @return String
	 */
	public String getRemoteIP(HttpServletRequest request) {
		if (request.getHeader("x-forwarded-for") == null) {
			return request.getRemoteAddr();
		}
		return request.getHeader("x-forwarded-for");
	}
}